from django.conf import settings


from django.utils.translation import ugettext_lazy as _
from com.ad.sword.dao.models import SystemLog
from com.ad.sword.web.common import *

class SwordLog:
    def __init__(self, request):
        self.log = []
        self.request = request

    def __log(self, severity = 'D', title = None, description = None):
        self.log.append(SystemLog(username = self.request.session.get('username', '*System*'), 
                            ip = self.request.META['REMOTE_ADDR'], severity = severity, 
                            title = title, description = description))
        
    def Debug(self, title, description = None):
        if settings.DEBUG:
            self.__log(title = title, description = description)

    def Info(self, title, description = None):
        self.__log(severity = "I", title = title, description = description)

    def Warning(self, title, description = None):
        self.__log(severity = "W", title = title, description = description)

    def Error(self, title, description = None):
        self.__log(severity = "E", title = title, description = description)

    def Critical(self, title, description = None):
        self.__log(severity = "C", title = title, description = description)

    def save(self):
        for l in self.log:
            try:
                l.save()
            except:
                if settings.DEBUG:
                    raise
                else:
                    pass
                
class LogMiddleware(object):
    def process_request(self, request):
        request.log = SwordLog(request)

    def process_response(self, request, response):
        request.log.save()        
        return response

@tojson
def list(request):
    log = string_ifilter(request, SystemLog.objects, ["severity"])
    log = time_filter(request, log, ["time"])
    page_no = int(request.REQUEST.get("page_no", 0))
    page_size = int(request.REQUEST.get("page_size", 40))


    logs = {"items": [], "page_size": page_size, "page_no": page_no, "count": log.count()}
    for i in log.all().order_by("-time")[page_no * page_size: (page_no + 1) * page_size]:
        a = {}
        for k in i:
            if k == "id":
                a[k] = int(i[k])
            elif k == "time":
                a[k] = time2str(i[k])
            else:
                a[k] = unicode(i[k])
        logs['items'].append(a)

    return logs


@check_login
def export(request):
    from excel_response import ExcelResponse

    log = string_ifilter(request, SystemLog.objects, ["severity"])
    log = time_filter(request, log, ["time"])
    page_no = int(request.REQUEST.get("page_no", 0))
    page_size = int(request.REQUEST.get("page_size", 2000))

    logs = SystemLog.all().order_by("-time")[page_no * page_size: (page_no + 1) * page_size]
    if len(logs) == 0:
        return tab2json(request, error_msg(code = 204, msg=_("No log found")))
    else:
        return ExcelResponse(logs, time2str(datetime.now()))

@tojson
def purge(request):
    logs=SystemLog.objects()
    for log in logs:
        log.delete()
    return message(_("OK"))


@tojson
@check_required_argument
def delete(request):
    ids = get_required_argument(request, "id").split(',')
    for id in ids:
        log=SystemLog.objects.get(id=id)
        log.delete()
    return message(_("OK"))



@tojson
@from_local
def clear(request):
    days=get_int_config('alarm_max_days', 90)
    expire=time2str(datetime.now() - timedelta(days=days))
    logs=SystemLog.objects(time__lt=expire)
    if len(logs)>0:
        request.log.Info(title=_("Clear System Log"))
    for a in logs:
        a.delete()
    
    return message(_("OK")) 




